package party.lovey.remote.utils;

import javax.imageio.ImageIO;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;

/**
 * Created by huhaichao on 2017/3/19.
 */
public class ImageUtil {

    public static byte[] toBytes(BufferedImage image) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();

    }

    public static BufferedImage fromBytes(byte[] bytes) {
        try {
            return ImageIO.read(new ByteArrayInputStream(bytes));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static boolean saveToPath(BufferedImage image, String path) {
        try {
            ImageIO.write(image, Consts.JPG, new File(path + new Date().getTime() + ".jpg"));
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取灰度图像的字节数组
     *
     * @param image
     * @return
     */
    public static byte[] getMatrixGray(BufferedImage image) {
        // 转灰度图像
        BufferedImage grayImage = new BufferedImage(image.getWidth(), image.getHeight(),
                BufferedImage.TYPE_BYTE_GRAY);
        new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null).filter(image, grayImage);
        // getData方法返回BufferedImage的raster成员对象
        return (byte[]) grayImage.getData().getDataElements(0, 0, image.getWidth(), image.getHeight(), null);
    }

    /**
     * 获取图像RGB格式数据
     *
     * @param image
     * @return
     */
    public static byte[] getMatrixRGB(BufferedImage image) {
        if (image.getType() != BufferedImage.TYPE_3BYTE_BGR) {
            // 转sRGB格式
            BufferedImage rgbImage = new BufferedImage(
                    image.getWidth(),
                    image.getHeight(),
                    BufferedImage.TYPE_3BYTE_BGR);
            new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(image, rgbImage);
            // 从Raster对象中获取字节数组
            return (byte[]) rgbImage.getData().getDataElements(0, 0, rgbImage.getWidth(), rgbImage.getHeight(), null);
        } else {
            return (byte[]) image.getData().getDataElements(0, 0, image.getWidth(), image.getHeight(), null);
        }
    }

    /**
     * 彩色转换为黑白
     *
     * @param image
     * @return
     */
    public static BufferedImage revertImage(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb = image.getRGB(x, y);
                int r = (rgb & 0xff0000) >> 16;
                int g = (rgb & 0xff00) >> 8;
                int b = (rgb & 0xff);
                int avg = (r + g + b) / 3;

                r = g = b = avg;
                int newRgb = (r * 256 + g) * 256 + b;
                if (newRgb > 8388608) {
                    newRgb -= -16777216;
                }
                image.setRGB(x, y, newRgb);
            }
        }
        return image;
    }

    /**
     * 转换为纯黑纯白
     * @param image
     * @return
     */
    public static BufferedImage revertImage2(BufferedImage image) {

        int width = image.getWidth();
        int height = image.getHeight();
        boolean forward=true;
        int[] before=new int[10000];
        int cur=0;
        for (int x = 0; x < width;x++) {

            //扫描下列时，调整方向
            forward=!forward;

            for (int y1 = 0; y1 < height; y1++) {
                int y;
                if(forward){
                    y=y1;
                }else {
                    y=height-y1-1;
                }
                int rgb = image.getRGB(x, y);
                int r = (rgb & 0xff0000) >> 16;
                int g = (rgb & 0xff00) >> 8;
                int b = (rgb & 0xff);
                int avg = (r + g + b) / 3;
                before[++cur%before.length]=avg;
                int avgBefore=avg(before);

                if (avg >= avgBefore) {
                    r = g = b = 255;

                } else {
                    r = g = b = 0;

                }


                int newRgb = (r * 256 + g) * 256 + b;
                if (newRgb > 8388608) {
                    newRgb -= -16777216;
                }
                image.setRGB(x, y, newRgb);
            }
        }
        return image;
    }

    private static int avg(int[] before) {
       return Arrays.stream(before).parallel().sum()/before.length;
    }

}

